package com.carkeeper.shop.service.impl;

import com.carkeeper.shop.dao.StoreMapper;
import com.carkeeper.shop.pojo.Store;
import com.carkeeper.shop.service.StoreService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreMapper storeMapper;

    @Override
    public List<Store> findAll() {

        return storeMapper.selectAll();
    }

    @Override
    public Page<Store> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Store>) storeMapper.selectByExample(example);
    }

    @Override
    public void addStore(Store store) {
        storeMapper.insertSelective(store);
    }

    @Override
    public void updateStore(Store store) {
        storeMapper.updateByPrimaryKey(store);
    }

    @Override
    public Store findStoreById(String id) {
        return storeMapper.selectByPrimaryKey(id);
    }


    /**
     * 构建查询对象
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Store.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 汽修厂简称
            if(searchMap.get("simpleName")!=null && !"".equals(searchMap.get("simpleName"))){
                criteria.andLike("simpleName","%"+searchMap.get("simpleName")+"%");
            }
            // 汽修厂编码
            if(searchMap.get("code")!=null && !"".equals(searchMap.get("code"))){
                criteria.andEqualTo("code",searchMap.get("code"));
            }
            // 省，城市，区县
            if(searchMap.get("province")!=null && !"".equals(searchMap.get("province"))){
                criteria.andEqualTo("province",searchMap.get("province"));
            }

            if(searchMap.get("city")!=null && !"".equals(searchMap.get("city"))){
                criteria.andEqualTo("city",searchMap.get("city"));
            }

            if(searchMap.get("county")!=null && !"".equals(searchMap.get("county"))){
                criteria.andEqualTo("county",searchMap.get("county"));
            }

            // 联系电话
            if(searchMap.get("contactPhone")!=null ){
                criteria.andEqualTo("contactPhone",searchMap.get("contactPhone"));
            }
            // 是否连锁
            if(searchMap.get("isChain")!=null ){
                criteria.andEqualTo("isChain",searchMap.get("isChain"));
            }

            // 状态
            if(searchMap.get("status")!=null ){
                criteria.andEqualTo("status",searchMap.get("status"));
            }

        }
        return example;
    }
}
